import {Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
import {Util} from "../../../common/util";
import {InterbankService} from "../interbank.service";
import {Subscription} from "rxjs/Subscription";
import * as _ from "lodash";

export interface NettingCountResultModel {
  sch: {
    list?: Array<{ [propName: string]: any }>;
    result?: any;
    resultDesc?: any;
    balance?: any;
    [propName: string]: any;
  };
  cbc: {
    list?: Array<{ [propName: string]: any }>;
    result?: any;
    resultDesc?: any;
    balance?: any;
    [propName: string]: any;
  };
}

/**
 * 银行间----轧差计算组件
 */
@Component({
  selector: 'interbank-netting-count',
  templateUrl: './netting-count.component.html',
  styleUrls: ['./netting-count.component.scss']
})
export class NettingCountComponent implements OnInit {

  public modalStatus: boolean;

  public get schListStatus(): boolean {
    return _.get(this.data, 'sch.list', []).length > 0;
  }

  public get cbcListStatus(): boolean {
    return _.get(this.data, 'cbc.list', []).length > 0;
  }

  @Input()
  public data: NettingCountResultModel;

  @Input()
  public willNettingCountData: Array<{ [propName: string]: any }>;

  @Output('close')
  public closeEmitter: EventEmitter<any> = new EventEmitter();

  @Output('save')
  public saveEmitter: EventEmitter<any> = new EventEmitter();

  @ViewChild("modal")
  public modal: ElementRef;

  constructor(public service: InterbankService) {
  }

  ngOnInit() {
  }

  public openModal(): void {
    this.modalStatus = true;
    Util.$(this.modal.nativeElement).modal('show');
  }

  /**
   *
   * @param clearWillNettingCountData 关闭模态框后是否立即清空clearWillNettingCountData数据的表示，true表示立即清空，
   * false表示不清空
   */
  public closeModal(clearWillNettingCountData: boolean = true): void {
    this.modalStatus = false;
    Util.$(this.modal.nativeElement).modal('hide');
    this.closeEmitter.emit(clearWillNettingCountData);
  }

  public toggleModal(): void {
    this.modalStatus = !this.modalStatus;
    Util.$(this.modal.nativeElement).modal('toggle');
  }

  /**
   * 保持扎差结果
   * @returns {Subscription}
   */
  public saveNettingCountResult(): Subscription {
    const orderSerialNos: Array<any> = this.willNettingCountData.map((item) => {
      return {orderSerialNo: item.orderSerialNo};
    });
    this.closeModal(false);
    return this.service.nettingCount(orderSerialNos, true).subscribe(data => {
      if (data != null) {
        this.closeEmitter.emit(true);
        this.saveEmitter.emit(true);
        window['swal']("提示", "已成功保存轧差计算！", "success");
      } else {
        window['swal']("警告", `保存轧差计算失败！`, "warning");
      }

    });
  }
}
